package com.xwdeshj.utils;


import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by BKWJA on 2018/10/18.
 * 自动捕获异常，并调整到错误页面，Service 层异常和数据校验异常的示例
 */
@ControllerAdvice  //注解定义全局异常处理类
public class IMoocExceptionHandler {

    public static final String IMOOC_ERROR_VIEW = "404.html";

//    @ExceptionHandler(value = Exception.class)  //可以直接写@ExceptionHandler,不指明异常类，会自动映射
//    public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{
//
//        ModelAndView mv = new ModelAndView();
//        e.printStackTrace();
//        mv.addObject("exception",e);
//        mv.addObject("url",request.getRequestURL());
//        mv.setViewName(IMOOC_ERROR_VIEW);
//        return mv;
//    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object errorHandler(HttpServletRequest reqest, HttpServletResponse response, Exception e) throws Exception {

        e.printStackTrace();

        if (isAjax(reqest)) {
//            return IMoocJSONResult.errorException(e.getMessage());
            Map<String, Object> modelMap = new HashMap<String, Object>();
            modelMap.put("status", 555);
            modelMap.put("msg", e.getMessage());
            return modelMap;
        } else {
            ModelAndView mav = new ModelAndView();
            mav.addObject("message", e.getMessage());
            mav.addObject("url", reqest.getRequestURL());
            mav.setViewName(IMOOC_ERROR_VIEW);
            return mav;
        }
    }

//    //统一异常处理类
//    private Map<String,Object> exceptionHandler(HttpServletRequest request,Exception e) {
//        Map<String, Object> modelMap = new HashMap<String, Object>();
//        modelMap.put("status", 555);
//        modelMap.put("msg", e.getMessage());
//        return modelMap;
//    }

    /**
     *
     * @Title: IMoocExceptionHandler.java
     * @Package com.imooc.exception
     * @Description: 判断是否是ajax请求
     * Copyright: Copyright (c) 2017
     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
     *
     * @author leechenxiang
     * @date 2017年12月3日 下午1:40:39
     * @version V1.0
     */
    public static boolean isAjax(HttpServletRequest httpRequest){
        return  (httpRequest.getHeader("X-Requested-With") != null
                && "XMLHttpRequest"
                .equals( httpRequest.getHeader("X-Requested-With").toString()) );
    }
}
